import os

from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer

from utils.spark.sound import rtasr, iat
from ws.settings import BASE_DIR


class SoundConsumer(WebsocketConsumer):
    def websocket_connect(self, message):
        # 有客户端来向后端发送websocket连接的请求时，自动触发。
        # 服务端允许和客户端创建连接。
        self.accept()
    def websocket_receive(self, message):
        # 浏览器基于websocket向后端发送数据，自动触发接收消息。
        print(message)
        self.send("##########start##########")
        # self.send("小天：")
        file_path = os.path.join(os.path.join(BASE_DIR, 'ws/static'), message['text'])
        # rtasr.send(self, file_path)
        iat.send(self, file_path)
        self.send("##########end##########")
        # self.close()

    def websocket_disconnect(self, message):
        # 客户端与服务端断开连接时，自动触发。
        print("断开连接")
        raise StopConsumer()

# import asyncio
# import websockets
#
# class SoundConsumer(AsyncWebsocketConsumer):
#
#     def __init__(self):
#         self.websocket = None
#         self.app_id = '41957fc4'
#         self.api_key = 'de8b98afd989a0b3797b10d2ca7d5b4b'
#     async def websocket_connect(self, event):
#         # 建立 WebSocket 连接
#         self.websocket = await self.accept()
#
#         base_url = "ws://rtasr.xfyun.cn/v1/ws"
#         ts = str(int(time.time()))
#         tt = (self.app_id + ts).encode('utf-8')
#         md5 = hashlib.md5()
#         md5.update(tt)
#         baseString = md5.hexdigest()
#         baseString = bytes(baseString, encoding='utf-8')
#
#         apiKey = self.api_key.encode('utf-8')
#         signa = hmac.new(apiKey, baseString, hashlib.sha1).digest()
#         signa = base64.b64encode(signa)
#         signa = str(signa, 'utf-8')
#         self.end_tag = "{\"end\": true}"
#
#         # 连接讯飞语音识别的 WebSocket
#         self.ifly_websocket = await websockets.connect(base_url + "?appid=" + self.app_id + "&ts=" + ts + "&signa=" + quote(signa))
#
#         file_object = open(os.path.join(os.path.join(BASE_DIR, 'httpApp/static'),'test.pcm'), 'rb')
#         try:
#             index = 1
#             while True:
#                 chunk = file_object.read(1280)
#                 if not chunk:
#                     break
#                 self.ifly_websocket.send(chunk)
#
#                 index += 1
#                 time.sleep(0.04)
#         finally:
#             file_object.close()
#
#         self.ifly_websocket.send(bytes(self.end_tag.encode('utf-8')))
#
#
#         # 启动消息转发任务
#         forward_task = asyncio.create_task(self.forward_messages())
#
#         # 不断接收前端 WebSocket 的消息并发送给讯飞语音识别的 WebSocket
#         # async for message in self.websocket:
#         #     await self.ifly_websocket.send(message)
#
#         # 等待消息转发任务完成
#         await forward_task
#
#     async def forward_messages(self):
#         try:
#             res = []
#             # 不断接收讯飞语音识别的 WebSocket 的消息并发送给前端 WebSocket
#             while self.ifly_websocket.open:
#                 try:
#                     message = await self.ifly_websocket.recv()
#                     # 处理接收到的消息
#                     result = str(message)
#                     if len(result) == 0:
#                         print("receive result end")
#                         break
#                     result_dict = json.loads(result)
#                     # 解析结果
#                     if result_dict["action"] == "started":
#                         res.clear()
#                         print("handshake success, result: " + result)
#
#                     if result_dict["action"] == "result":
#                         result_1 = json.loads(result_dict["data"])["cn"]["st"]["rt"]
#                         res.append(''.join([item['cw'][0]['w'] for item in result_1[0]['ws']]))
#
#                     if result_dict["action"] == "error":
#                         print("rtasr error: " + result)
#                         self.ifly_websocket.close()
#                         res.clear()
#                     print(res)
#                 except websocket.WebSocketConnectionClosedException:
#                     print("receive result end")
#                 # await self.websocket.send("aaaaa")
#
#         except websockets.exceptions.ConnectionClosedOK:
#             # 如果讯飞语音识别的 WebSocket 连接关闭，关闭前端 WebSocket 连接
#             await self.websocket.close()
#
#     async def websocket_disconnect(self, event):
#         # 关闭 WebSocket 连接
#         await self.websocket.close()
#         await self.ifly_websocket.close()